package com.elsa.DataStatistics.statistics;

import com.elsa.DataStatistics.mapper.*;
import com.elsa.DataStatistics.pojo.*;
import com.elsa.DataStatistics.utils.CalculateUtil;
import com.elsa.DataStatistics.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class DayMenuStatistics {

    @Autowired
    private TimeUtil timeUtil;

    @Autowired
    private DayMapper dayMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DayMenuMapper dayMenuMapper;

    @Autowired
    private CalculateUtil calculateUtil;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuOrderMapper menuOrderMapper;

    public void dayStatistics(String oId) {

        int dId = timeUtil.getDayTime();

        List<MenuOrder> menuOrderList = menuOrderMapper.selectMenuOrderMapperFromOrderDataStatistics(oId);

        for (int i = 0; i < menuOrderList.size(); i++) {
            DayMenu dayMenu = dayMenuMapper.selectDayMenuMapperFromDIdAndMId(dId, menuOrderList.get(i).getMId());
            if(dayMenu == null) {
                dayMenu = new DayMenu();
                dayMenu.setDmId(dayMenuMapper.selectCount(null) + 1);
                dayMenu.setDId(dId);
                dayMenu.setMId(menuOrderList.get(i).getMId());
                dayMenu.setMName(menuOrderList.get(i).getMName());
                Menu menu = menuMapper.selectById(menuOrderList.get(i).getMId());
                dayMenu.setDmIncome(menu.getMPrice() * menuOrderList.get(i).getMoNum());
                dayMenu.setDmExpand(menu.getMOldPrice() * menuOrderList.get(i).getMoNum());
                double profit = dayMenu.getDmIncome() - dayMenu.getDmExpand();
                dayMenu.setDmProfit(profit);
                dayMenu.setDmNum(menuOrderList.get(i).getMoNum());
                log.info(String.valueOf(dayMenu));
                dayMenuMapper.insert(dayMenu);
            } else {
                Menu menu = menuMapper.selectById(menuOrderList.get(i).getMId());
                dayMenu.setDmId(dayMenu.getDmId());
                dayMenu.setMName(menuOrderList.get(i).getMName());
                dayMenu.setDmIncome(dayMenu.getDmIncome() + menu.getMPrice() * menuOrderList.get(i).getMoNum());
                dayMenu.setDmExpand(dayMenu.getDmExpand() + menu.getMOldPrice() * menuOrderList.get(i).getMoNum());
                double profit = (menu.getMPrice() * menuOrderList.get(i).getMoNum()) - (menu.getMOldPrice() * menuOrderList.get(i).getMoNum());
                dayMenu.setDmProfit(dayMenu.getDmProfit() + profit);
                dayMenu.setDmNum(dayMenu.getDmNum() + menuOrderList.get(i).getMoNum());
                log.info(String.valueOf(dayMenu));
                dayMenuMapper.updateById(dayMenu);
            }
        }
    }

}
